/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-06-24 14:34:57
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-10-27 08:30:56
 * @FilePath: \keep_motion_api\models\user\user.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose'); // 引入 mongoose 模块;
const Schema = mongoose.Schema; // 获取 Schema 对象;
const { escapeRegex, wxLogin } = require('@/utils');
const { generateToken } = require('@/middleWares/auth/jwt.js');
// 用户基础模型 (users)
const userSchema = new Schema({
  // openid: { type: String, required: true, unique: true },
  // session_key: { type: String, required: true },
  openid: { type: String, unique: true },
  session_key: { type: String},
  username: { type: String, unique: true }, 
  password: { type: String},
  name: String,
  phone: String,
  email: String,
  avatar: { 
    type: String, 
    default: '/default-avatar.png' 
  },
  register_time: { type: Date, default: Date.now },
  status: {
    type: String,
    enum: ["active", "frozen", "deleted"],
    default: "active"
  },
  health_data: {
    height: Number,
    weight_history: [{
      value: Number,
      date: Date
    }],
    body_fat_rate: Number
  },
  health_assessments: [{
    type: Schema.Types.ObjectId,
    ref: 'HealthAssess'
  }],
  enrolled_courses: [{
    type: Schema.Types.ObjectId,
    ref: 'Course'
  }],
  course_progress: [{
    type: Schema.Types.ObjectId,
    ref: 'CourseProgress'
  }]
});
userSchema.statics.getUsers = async function (name, phone, status, offset, limit) {
  try {
    const query = {};
    if (name) {
      const escapedName = escapeRegex(name);
      query.name = { $regex: escapedName, $options: 'i' };
    }
    if (phone) {
      const escapedPhone = escapeRegex(phone);
      query.phone = { $regex: escapedPhone, $options: 'i' };
    }
    if (status) query.status = status;
    const total = await this.countDocuments(query);
    const rows = await this.find(query)
        .skip(Number(offset))
        .limit(Number(limit));
    return { rows, total };
  } catch (error) {
    throw error;
  } 
}
userSchema.statics.createUser = async function (username, password, name, phone, email, avatar, status) {
  try {
    const user = await this.create({username, password, name, phone, email, avatar, status});
    if (!user) {
      throw new Error('用户创建失败');
    }
    const { Finance } = require('./index');
    await Finance.create({
      user_id: user._id,
      balance: 0,
      last_payment_date: new Date()
    });
    return user;
  } catch (error) {
    throw error;
  }
}
userSchema.statics.updateUser = async function (id, username, password, name, phone, email, avatar, status) {
  try {
    return await this.findByIdAndUpdate(id, {username, password, name, phone, email, avatar, status}, { new: true });
  } catch (error) {
    throw error;
  }
}
userSchema.statics.deleteUser = async function (id) {
  try {
    return await this.findByIdAndUpdate(id, { status: 'deleted' }, { new: true });
  } catch (error) {
    throw error;
  }
}
userSchema.statics.updateUserAvatar = async function (id, avatar) {
  try {
    return await this.findByIdAndUpdate(id, { avatar }, { new: true });
  } catch (error) {
    throw error;
  }
}
userSchema.statics.wxLogin = async function (code) {
  try {
    const wxLoginResult = await wxLogin(code);
    const { openid, session_key } = wxLoginResult;
    let user = await this.findOne({ openid });
    if (!user) {
      user = await this.create({
        name: '新人入队',
        avatar: 'uploads\\default-avatar.png',
        openid,
        session_key,
        register_time: new Date()
      });
    }
    const token = generateToken({ userId: user._id });
    user = {
      token,
      name: user.name,
      avatar: user.avatar,
      phone: user.phone,
      email: user.email,
    };
    return user;
  } catch (error) {
    throw error;
  }
}

// 导出所有模型
module.exports = mongoose.model('User', userSchema);